#include "GameData.h"

CGameData::CGameData() {
	nodes = new map<int, CNode*>();
	MapGameObjects = new map<int, GameObjectData*>();
}

void CGameData::getMapDataFromFile(LPWSTR FilePath) {
	ifstream file(FilePath);
	string line;
	vector<double> data;

	//Get list object
	getline(file, line);
	data = stringOption(line);
	ObjectCount = data.at(0);
	int index = _OBS_INDEX;

	//
	int id;
	int type;
	int limitLeft;
	int limitRight;
	double x, y, width, height;
	//
	for(int i = 0; i < ObjectCount; i++)
	{
		id = data[index++];
		type = data[index++];
		width = data[index++];
		height = data[index++];
		x = data[index++];
		y = data[index++];
		limitLeft = data[index++];
		limitRight = data[index++];
		MapGameObjects->insert(pair<int, GameObjectData*>(id, new GameObjectData(id, type, new Rect(x, y,width, height), limitLeft, limitRight)));
	}
	//Get quadtree

	CNode* node;
	AbstractEntity* entity;
	GameObjectData* objectdata;
	while(getline(file, line))
	{
		if(line != "")
		{
			index = 0;
			data = stringOption(line);
			id = data.at(index++);
			width = data.at(index++);
			height = data.at(index++);
			x = data.at(index++);
			y = data.at(index++);
			node = new CNode(id, new Rect(x, y, height, width));
			//Get object in node
			while (index < data.size())
			{
				objectdata = MapGameObjects->at(data.at(index++));
				entity = EntityAdapter::convertFromGameObjectData(objectdata);
				if (entity == NULL) continue;
				node->addGameObjects(entity);
			}
			//Add node to nodes
			nodes->insert(make_pair(id, node));
		}

	}


}

vector<double> CGameData::stringOption(string str)
{
	vector<double> result;

	int pos;
	while((pos = str.find_first_of(" ")) != -1)
	{
		string s = str.substr(0,pos);
		double d = stod(str.substr(0,pos).c_str());
		result.push_back(stod(str.substr(0,pos).c_str()));
		str = str.substr(pos + 1);
	}
	if(str != "")
	{
		result.push_back(stod(str.c_str()));
	}

	return result;
}